<template>
  <el-dialog v-model="state.isFalse" :title="publicStore.active.name + ' - 人员信息采集'" :before-close="onVisable" :draggable="true" width="750">
    <div class="layout-col">
      <el-form ref="formRef" :model="state.form" :rules="state.ruleList" label-width="85px">
        <el-form-item class="flex-sc" label="采集器" prop="sensor_id">
          <el-select size="large" v-model="state.form.sensor_id" placeholder="请选择" style="width:100%" clearable>
            <el-option  v-for="(v, i) in state.sensorList" :key="v.id" :label="'【' + v.stationNum + '号站】' + v.name" :value="v.id" />
          </el-select>
        </el-form-item>
        <el-form-item class="flex-ss" label="ID卡号" prop="rfid_card">
          <el-input class="flex1 pr15" size="large" v-model="state.form.rfid_card" placeholder="请录入ID卡号" />
          <el-button size="large" type="info" class="white bgi22" @click.stop="remote('card')" v-loading="state.loading && state.code == 'card'">{{state.form.rfid_card? '修 改': '录 入'}}</el-button>
          <el-button size="large" type="info" class="white bgi22" @click.stop="remoteEnd()" v-if="state.loading && state.code == 'card'">取消</el-button>
        </el-form-item>
        <el-form-item class="flex-ss" label="指纹" prop="finger_print">
          <div v-for="(v, i) in state.form.finger_print" :key="i" class="flex-bc flex1" :class="i==0?'':'pl15'">
            <div class="flex1" v-if="!isNull(state.form.finger_print[i])"><img class="h50x2" src="@/assets/images/finger.png" /></div>
            <el-input v-else class="flex1 pr15" size="large" v-model="state.form.finger_print[i]" :placeholder="'请录入指纹'+(i+1)" :disabled="true" />
            <el-button size="large" type="info" class="white bgi22" @click.stop="remote('fingerPrint' + (i+1))" v-loading="state.loading && state.code == 'fingerPrint'+ (i+1)">{{state.form.finger_print[i]? '修 改': '录 入'}}</el-button>
            <el-button size="large" type="info" class="white bgi22" @click.stop="remoteEnd()" v-if="state.loading && state.code == 'fingerPrint'+ (i+1)">取消</el-button>
          </div>
        </el-form-item>
        <el-form-item class="flex-ss" label="人面" prop="face_image">
          <div class="flex1">
            <el-image v-if="!isNull(state.form.face_image)" class="h100x2" :src="'data:image/png;base64,' + state.form.face_image" />
            <el-input v-else class="flex1 pr15" size="large" v-model="state.form.face_image" placeholder="请录入人脸" :disabled="true" />
          </div>
          <el-button size="large" type="info" class="white bgi22" @click.stop="remote('face')" v-loading="state.loading && state.code == 'face'">{{state.form.face_image? '修 改': '录 入'}}</el-button>
          <el-button size="large" type="info" class="white bgi22" @click.stop="remoteEnd()" v-if="state.loading && state.code == 'face'">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button size="large" type="info" class="i23 bg-white" @click="onVisable">取 消</el-button>
        <el-button size="large" type="info" class="white bgi22" @click.stop="handleSubmit(formRef)">保 存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
  import api from '../api'
  const { proxy }:any = getCurrentInstance()
  const publicStore = proxy.publicStore()
  const configStore = proxy.configStore()
  const emit = defineEmits(['init'])
  const state = reactive({
	  ...publicStore.$state,
    ruleList: {},
    interval: null,
    code: '',
    sensorList: [],
  })
  let formRef = $ref()
  const svg = `<path class="path" d=" M 30 15 L 28 17 M 25.61 25.61 A 15 15, 0, 0, 1, 15 30 A 15 15, 0, 1, 1, 27.99 7.5 L 15 15
       " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>`

  const onVisable = async (val) => {
    configStore.ip = ''
    state.isFalse = !state.isFalse
    remoteEnd()
    if(!state.isFalse) return
    state.form = Object.assign({}, val)
    state.form.finger_print = state.form.finger_print.split(",")
    let len = 3 - state.form.finger_print.length
    if(len != 0){
      console.log('补全finger_print', 3-state.form.finger_print.length)
      for(let i = 0; i < len; i++) {
        state.form.finger_print.push('')
      }
    }
    console.log('state.form', state.form)
    await init()
    if(!proxy.isNull(state.sensorList)) state.form.sensor_id = state.sensorList[0].id
  }

  const init = async() => {
    let params = {queryApi: getQuery()}
    let res = await publicStore.post(params)
    state.sensorList = proxy.isNull(res)? [] : res.filter(a=>a.class == '0')
  }

  const getQuery = () => {
    let queryArr = []
    if(publicStore.active.node_type == 1){
      let query = {"o": "o_sensor",	"p": [publicStore.active.id, "EICollector"], "i": 12}
      queryArr.push(query)
    }else{
      if(!proxy.isNull(configStore.stationList)) {
        let nodes = proxy.childrenId(configStore.stationList, publicStore.active.id, 'id')
        nodes.forEach(v => {
          let query = {"o": "o_sensor",	"p": [v, "EICollector"], "i": 12}
          queryArr.push(query)
        })
      }
    }
    return queryArr
  }

  const remoteEnd = async() => {
    configStore.ip = ''
    clearInterval(state.interval)
    state.code = ''
    state.time = 0
    state.loading = false
  }

  const remote = async(code) => {
    if(proxy.isNull(state.form.sensor_id)) return ElNotification({ title: '提示', message: '请选择采集器', type: 'error' })
    remoteEnd()
    state.code = code
    let allForm = {"sensor_id": state.form.sensor_id, "code": state.code.indexOf('fingerPrint')!=-1?'fingerPrint':state.code, "action": "1" }
    let node = proxy.parentNodes(publicStore._public.tree, state.form.sensor_id, 'id')
    let sensor = node.filter(a=>a.class == 2)
    if (!proxy.isNull(sensor) && !proxy.isNull(sensor[0].localSvcIP)) configStore.ip = sensor[0].localSvcIP + ':8808'
    api.remote([allForm]).then((res: any) => {
      getRemoteRes()
      clearInterval(state.interval)
      state.loading = true
      state.time = new Date().getTime()
      state.interval = setInterval(async () => {
        getRemoteRes()
      }, 1000)
    }).catch((err: any) => {
      remoteEnd()
      return ElNotification({ title: '提示', message: '采集失败', type: 'error' })
    })
  }

  const getRemoteRes = async() => {
    let query = [{"o":"o_r_sensor","p":[state.form.sensor_id],"i":1}]
    let params = {queryApi: query}
    let res = await publicStore.post(params)
    console.log('res.timestamp', parseInt(res[0].timestamp) - state.time)
    if(proxy.isNull(res) || proxy.isNull(res[0].timestamp)) return
    console.log('成功-----', res)
    if(state.code == 'card') {
      if(proxy.isNull(res[0].card_tc) || parseInt(res[0].card_tc) < state.time) return
      state.form.rfid_card = res[0][state.code]
    }
    if(state.code == 'fingerPrint1') {
      if(proxy.isNull(res[0].fingerPrint_tc) || parseInt(res[0].fingerPrint_tc) < state.time) return
      state.form.finger_print[0] = res[0].fingerPrint
    }
    if(state.code == 'fingerPrint2') {
      if(proxy.isNull(res[0].fingerPrint_tc) || parseInt(res[0].fingerPrint_tc) < state.time) return
      state.form.finger_print[1] = res[0].fingerPrint
    }
    if(state.code == 'fingerPrint3') {
      if(proxy.isNull(res[0].fingerPrint_tc) || parseInt(res[0].fingerPrint_tc) < state.time) return
      state.form.finger_print[2] = res[0].fingerPrint
    }
    if(state.code == 'face') {
      if(proxy.isNull(res[0].face_tc) || parseInt(res[0].face_tc) < state.time) return
      state.form.face_image = res[0][state.code]
    } 
    ElNotification({ title: '提示', message: '录入成功', type: 'success' })
    remoteEnd()
  }

  const handleSubmit =(formEl) => {
    formEl.validate(async valid =>{
      let form = Object.assign({}, state.form)
      let finger_show = false
      form.finger_print.forEach(v => {if(!proxy.isNull(v)) finger_show = true})
      form.finger_print = finger_show? form.finger_print.join() : ''
      delete form.sensor_id
      form.o = "o_comm_usr"
      form.t = "upd"
      form.a = "修改"
      let allForm = [form]
      api.updateApi(allForm).then((res:any) => {
        if(res.errcode == 0){
          ElNotification({ title: '提示', message: '操作成功', type: 'success' })
          emit('init')
          onVisable()
        }
      }).catch((err) => {
        ElNotification({ title: '提示', message: '操作失败', type: 'error' })
      })
	  }).catch((err:any) =>{
			state.loading = false
		  console.log('表单错误信息：', err);
	  })
  }
 
  // 暴露给父组件
  defineExpose({
    onVisable
  })
</script>

<style scoped lang="scss">

</style>
